<template>
  <div>
    <el-dialog
      :model-value="visible"
      :title="dept.id != undefined ? '编辑部门' : '添加部门'"
      width="500"
      :close-on-click-modal="false"
      @close="cls"
    >
      <el-form ref="formDept" :model="dept" :rules="rules">
        <el-form-item label="上级部门">
          <el-input v-model="dept.parentName" disabled />
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="dept.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cls">关闭</el-button>
          <el-button type="primary" @click="save"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { saveDept, updateDept } from "@/api/system/dept.js";
const dept = ref({
  id: undefined,
  name: "",
  parentid: 0,
  parentName: ""
});

//定义组件属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: true
  },
  isSaver: {
    type: Boolean,
    default: true
  }
});

//同名引用
const formDept = ref(null);
const rules = reactive({
  name: [{ required: true, message: "请输入部门名称", trigger: "blur" }]
});

//定义事件
const emits = defineEmits(["close", "reflush"]);
function cls() {
  emits("close");
  emits("reflush");
}

//初始化方法，用于传参
function init(pid, pname, id, name) {
  if (id != undefined) {
    dept.value.id = id;
    dept.value.name = name;
  } else {
    dept.value.name = "";
    dept.value.id = undefined;
  }

  dept.value.parentid = pid;
  dept.value.parentName = pname;
  if (pname == undefined) dept.value.parentName = "顶级部门";
}
//暴露init方法，方便父组件调用
defineExpose({ init });

//保存
async function save() {
  const valid = formDept.value.validate;
  if (!valid) return;
  let res = ref({});
  if (dept.value.id == undefined) {
    //发送数据
    res.value = await saveDept(dept.value);
  } else {
    res.value = await updateDept(dept.value);
  }
  if (res.value.code == 200) {
    ElMessage({
      message: "保存成功",
      type: "success"
    });
    cls();
  }
}
</script>
<style scoped></style>
